package com.hsyt.pms.security.service.impl;

import com.hsyt.pfc.support.rpc.PageResult;
import com.hsyt.pms.api.common.PageParam;
import com.hsyt.pms.security.dao.FunctionDao;
import com.hsyt.pms.security.entity.*;
import com.hsyt.pms.security.service.FunctionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;

@Service
public class FunctionServiceImpl implements FunctionService {

	@Autowired
	private FunctionDao fDao;


//	<util:map id="map">
//		<entry key="GatewayPlatform" value="互联网外联对接系统"></entry>
//		<entry key="Controller" value="控制中心"></entry>
//		<entry key="Configuration" value="配置中心"></entry>
//		<entry key="APIDocument" value="API文档"></entry>
//		<entry key="Businessdocument" value="业务文档"></entry>
//		<entry key="OpenDocument" value="开放文档"></entry>
//		<entry key="CenterRule" value="规则中心"></entry>
//		<entry key="Log" value="日志中心"></entry>
//		<entry key="Monitor" value="监控中心"></entry>
//		<entry key="InterfaceTest" value="接口测试平台"></entry>
//    </util:map>
	private static final HashMap stmap = new HashMap();
	static {
		stmap.put("GatewayPlatform","互联网外联对接系统");
		stmap.put("Controller","控制中心");
		stmap.put("Configuration","配置中心");
		stmap.put("APIDocument","API文档");
		stmap.put("Businessdocument","业务文档");
		stmap.put("OpenDocument","开放文档");
		stmap.put("CenterRule","规则中心");
		stmap.put("Log","日志中心");
		stmap.put("Monitor","监控中心");
	    stmap.put("InterfaceTest","接口测试平台");
	}
	/**
	 * @Title: getFunctionsByDto
	 * @Description: 根据Dto信息返回Function列表
	 * @param dto
	 * @return
	 */
	@Override
	public PageResult<Function> getFunctionsByDto(FunctionQueryDto dto) {
		PageParam.initPageDto(dto);
        List<Function> list = fDao.getFunctionsByDto(dto);
        PageResult<Function> result = new PageResult<Function>();
        result.setResult(true);
        result.setMessage("查询成功");
        result.setTotal(fDao.countFunctionByDto(dto));
        result.setRows(list);
        return result;
	}
	
	@Override
	public List<FunctionVo> getFunctionsByPlatform(String platformType){
		 List<FunctionVo> list = fDao.getFunctionsByPlatform(platformType);
		return list;
	}

	@Override
	public Collection<MenuDto> getMenuListNoType(boolean isSuper, Long userId) {
		// 获取所有的目录
		List<Function> list = new ArrayList<Function>();
		if(isSuper){
			FunctionQueryDto dto = new FunctionQueryDto();
			list = fDao.getFunctionsByDtoNoType(dto);
		}else{
			list = fDao.getPlatformAuthorityByUserId(userId,null);
		}
		return processToObj(list);
	}

	/**
	 * @Title: getFunctionList
	 * @Description: 返回权限菜单列表
	 * @param roleId（可选） platformType（可选）
	 * @return
	 */
	@Override
	public PageResult<FunctionVo> getFunctionList(Long roleId,String platformType) {
        List<FunctionVo> list = fDao.getFunctionsByPlatform(platformType);
        if(roleId == null){
        	 PageResult<FunctionVo> result = new PageResult<FunctionVo>();
             result.setResult(true);
             result.setMessage("查询成功");
             result.setRows(list);
             return result;
        }
        Assert.isTrue(roleId>=0,"roleId不合法");
        Long[] roleFunctionIds = fDao.getRoleFunctionRef(roleId);
        List<Long> asList = Arrays.asList(roleFunctionIds);
        for(FunctionVo vo:list){
        	if(asList.contains(vo.getId())){
        		vo.setChecked(true);
        	}
        }
        PageResult<FunctionVo> result = new PageResult<FunctionVo>();
        result.setResult(true);
        result.setMessage("查询成功");
        result.setRows(list);
        return result;
	}
	
	@Override
	public Collection<MenuDto> getMenuList(boolean isSuper,Long userId,String platformType){
		// 获取所有的目录
		List<Function> list = new ArrayList<Function>();
		if(isSuper){
			FunctionQueryDto dto = new FunctionQueryDto();
			dto.setPlatformType(platformType);
			dto.setSort("sortNum");
			dto.setOrder("ASC");
			dto.setPageSize(2000);
			dto.setStatus("enabled");
			list = fDao.getFunctionsByDto(dto);
		}else{
			list = fDao.getPlatformAuthorityByUserId(userId,platformType);
		}
		return processToObj(list);
	}
	

	@Override
	public Collection<MenuDto> processToObj(List<? extends Function> list){
		
		Map<String,MenuDto> map = new LinkedHashMap<String, MenuDto>();
		MenuDto menuDto = null;
		//抽出一级菜单
		for(Function func:list){
			if(func.getLevel() == 1){
				menuDto = new MenuDto(func);
				map.put(func.getCode(), menuDto);
			}
		}
		//填充二级菜单
		for(Function func:list){
			if(func.getLevel() == 2){
				MenuDto menu = map.get(func.getParentCode());
				if(menu !=null){
					menu.getChildMenus().add(func);
				}
			}
		}
		//去除无效的一级一级菜单
		Iterator<Map.Entry<String, MenuDto>> it = map.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry<String, MenuDto> entry = it.next();
			String url = entry.getValue().getMenu().getFunctionUrl();
			if(StringUtils.isBlank(url) && entry.getValue().getChildMenus().size() == 0){
				it.remove();
			}
		}
		return  map.values();
	}
	
	/**
     * @Title: insertFunctionSelective
     * @Description: 新增Function
     * @param func
     */
	@Transactional
	@Override
	public void insertFunctionSelective(Function func) {
		fDao.insertSelective(func);
	}
	
	/**
     * @Title: updateFunctionSelective
     * @Description: 通过主键Id更新Function
     * @param func
     */
	@Transactional
	@Override
	public void updateFunctionSelective(Function func) {
		fDao.updateByPrimaryKeySelective(func);
	}



	/**
     * @Title: isExistCode
     * @Description: 根据code判断是否存在Function
     * @param code
     */
	@Override
	public boolean isExistCode(String code) {
		Function function  = fDao.getFunctionByCode(code);
		return function != null;
	}
	
	/**
	 * <p>Title: isAvailableCode</p>
	 * <p>Description: 判断code是否可用</p>
	 * @param id
	 * @param code
	 * @return boolean
	 */
	@Override
	public boolean isAvailableCode(Long id, String code) {
		Function function = fDao.getFunctionByCode(code);
		return function==null?true:(function.getId().equals(id)?true:false);
	}
	/**
     * @Title: deleteFunctionsByPrimaryKey
     * @Description: 根据id数组批量删除菜单

     */
	@Transactional
	@Override
	public int deleteFunctionsByPrimaryKey(Long[] ids) {
		return fDao.deleteFunctionsByPrimaryKey(ids);
	}

	/**
	 * <p>Title: roleAuthorize</p>
	 * <p>Description: 通过角色id为角色授权</p>
	 * @param roleId
	 * @param ids

	 */
	@Transactional
	@Override
	public void roleAuthorize(Long roleId, Long[] ids) {
		List<RoleFunctionRefDto> dtos = new ArrayList<RoleFunctionRefDto>(ids.length);
		Date time =new Date();
		for(int i=0,l=ids.length;i<l;i++){
    		RoleFunctionRefDto dto = new RoleFunctionRefDto();
    		dto.setRoleId(roleId); 
    		dto.setFunctionId(ids[i]);
    		dto.setCreateTime(time);
    		dto.setUpdateTime(time);
    		dtos.add(dto);
    	}
		fDao.cleanDisabledAuthority(roleId, ids);
		fDao.roleAuthorize(dtos);
	}
	
	/**
	 * <p>Title: cleanDisabledAuthority</p>
	 * <p>Description: 给角色去除不在ids之中的权限</p>
	 * @param roleId
	 * @param ids
	 */
	@Transactional
	@Override
	public void cleanDisabledAuthority(Long roleId, Long[] ids){
		fDao.cleanDisabledAuthority(roleId, ids);
	}

	@Transactional
	@Override
	public int deleteFucntionByCode(String code) {
		return fDao.deleteFucntionByCode(code);
	}


	@Override
	public List<FunctionVo> getFunctionListByRoleId(Long roleId) {
		return fDao.getFunctionListByRoleId(roleId);
	}
}
